<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Libs\TokenLibrary;

/**
 * 验证token，并且过期自动刷新
 * Class AuthJwtToken
 * @package App\Http\Middleware
 */
class AuthJwtToken
{
     /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     * @throws JWTException
     */
    public function handle($request, Closure $next)
    {   
        dd($request);
        $authToken = $request->header('Authorization');
        if(!$authToken){
            return response(['code'=>401,'message'=>'请登录']);
        }
        try{
            $authToken = trim(ltrim($authToken,'bearer'));
            $res = TokenLibrary::validateToken($authToken);
            $data = (array)$res;
            $userinfo = (array)$data['data'];
            $token = cache()->get("token_front_".$userinfo['user_id'].'_'.$data['iat']);
            if(!$token || $authToken != $token){
                return response(['code'=>401,'message'=>'请重新登录']);
            }
            $request->user  = [
                'id' => $userinfo['user_id'],
                'user_no' => $userinfo['user_no'],
                'iat'=>$data['iat']
            ]; 
        }catch (\Exception $e){
            return response(['code'=>401,'message'=>'请重新登录']);
        }

        return $next($request);
    }


}
